package com.livew.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.livew.dao.UserMapper;
import com.livew.model.User;
import com.livew.redis.dao.RedisDao;
import com.livew.utils.JsonUtils;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private RedisDao<User> redisDao;

	@Override
	public void saveUser(User user) {
		userMapper.insertSelective(user);
	}

	@Override
	public List<User> getAllUser() {
		return userMapper.getAllUser();
	}

	@Override
	public User getUserById(Integer id) {
		String json = redisDao.get(USER_INFO + id);
		User user = null;
		if (!StringUtils.isEmpty(json)) {
			user = JsonUtils.fromJson(json, User.class);
			return user;
		} else {
			user = userMapper.getUserById(id);
			redisDao.set(USER_INFO+user.getId(), user);
		}
		return user;
	}

	@Override
	public void renameUser(String name, Integer id) {
		User user = userMapper.getUserById(id);
		user.setName(name);
		userMapper.renameUser(user);
		redisDao.set(USER_INFO+id, user);
	}

	@Override
	public void deleteUserById(Integer id) {
		userMapper.deleteUserById(id);
	}

}
